package org.jdns.jfreechess.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;

import javax.inject.Inject;

import org.jdns.jfreechess.timeseal.TimesealedMessage;

public class LoginHandler extends ChannelInboundMessageHandlerAdapter<TimesealedMessage> {
  private static final String LOGIN_PROMPT = "****** Welcome to the Free Internet Chess Server at freechess.org ******\n\rlogin: ";
  private static final String PASSWORD_PROMPT = "\n\rpassword: ";

  String username = null;
  private boolean passwordSent = false;

  private final ChessServer server;
  
  @Inject
  public LoginHandler(ChessServer server) {
    this.server = server;
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.write(LOGIN_PROMPT);
    ctx.flush();
  }

  @Override
  public void messageReceived(ChannelHandlerContext ctx, TimesealedMessage msg) throws Exception {
    System.out.println("login message received: " + msg);
    
    if (msg.getMessage().startsWith("%b")) {
      ctx.write("\n\r#Ivars set.\n\r");
      ctx.flush();
    } else if (!passwordSent) {
      ctx.write(PASSWORD_PROMPT);
      ctx.flush();
      username = msg.getMessage();
      System.out.println("username: " + username);
      passwordSent = true;
    } else {
      String password = msg.getMessage();
      System.out.println("password: " + password);

      // yay, they logged in!
      User user = User.authenticatedUser(ctx.channel(), username);
      ctx.channel().attr(User.CHANNEL_ATTRIBUTE_KEY).set(user);
      server.userConnected(user);

      // welcome the user
      ctx.write(String.format("**** Starting FICS session as %s ****", username));
      ctx.pipeline().remove(this);
      ctx.pipeline().addFirst(new PromptHandler());
      ctx.flush();
    }
  }
}
